import '../utils/formatTime.js';
import DpModal from '../components-business/dp-modal/dp-modal.vue';
import { DproHeader } from "../components/index";
import PicPanelTitle from '../components-business/pic-panel-title.vue';
import PicList from '../components-business/pic-list.vue';
import { API_URLS } from '../api/index.js';
import { requestApi, formatCardProps } from "../utils/util";
import widgetConfig from '../widget.config.json';
let propsConfig = Object.assign({}, widgetConfig.props);
const MAX_LENGTH = 10

Widget({
  props: {
    config: {
      type: String,
      default: () => {
        return JSON.stringify({
          isPub: 2,
          roleType: 2, // 2 企业主
          userId: '',
          accessToken: 'f0Y96v50FPoiElGOoHCj5fRMq87ynid5', // 业务token
        })
      }
    },
    card: {
      type: String,
      default: () => {
        return JSON.stringify({})
      }
    }
  },
  data() {
    return {
      widgetConfig,
      propsConfig,
      picList: [],
      loading: false,
      deviceCodes: '',
      cardInfo: {},
      actIndex:0
    };
  },
  mounted() {
    // 读取卡片props初始化参数并保存到配置文件中
    this.cardInfo = formatCardProps(this.$props, { cardName: this.propsConfig.title });

    this.fetchData()
  },
  // created() {
  //   // 浏览器本地调试注入wgt
  //   const script = document.createElement('script');
  //   script.src = 'https://dv.dlife.cn/digital/screen/preview/js/wgt-jssdk-1.0.3.js?t=1708564868451';
  //   script.async = true;
  //   script.onload = () => {
  //     WgtSDK.globalConfig({ clientId: 'devtools' })
  //   };
  //   document.head.appendChild(script);
  // },
  methods: {
    tabsFn(index){
      console.log("切换",index)
      this.actIndex = index
    },
    // 挂载容器
    getPopupContainer() {
      return this.$refs.absContainer;
    },
    saveCardDeviceInfo(cardName = this.cardInfo.cardName, deviceCodes = '') {
      requestApi({
        url: API_URLS.saveCardDeviceInfo,
        method: 'post',
        data: { screenId: this.cardInfo.screenId, cardId: this.cardInfo.cardId, cardName, cardSeq: this.cardInfo.index, deviceCodes },
        headers: {
          AccessToken: this.cardInfo.accessToken
        }
      }).then(res => {
        if (res.code === 0) {
          wgt.showMessage({
            title: '配置成功',
            icon: 'success',
            duration: 3000
          });
          this.getCardDeviceInfo()
          this.$refs.picPanelTitle?.closeSettingModal();
        }
      }).catch(err => {
        wgt.showMessage({
          title: err.msg,
          icon: 'error',
          duration: 3000
        });
      })
    },
    refresh() {
      this.getDataList()
    },
    async fetchData() {
      this.loading = true;
      await this.getDataList();
      this.loading = false
    },

    // 获取格式化业务响应数据
    async getDataList() {
      requestApi({
        url: API_URLS.getTypeInfo,
        method: 'post',
        // data:{
        //   'queryParams':{
        //     "sceneType":3 //疑似高危就医人员
        //   }
        // },
        headers: {
          AccessToken: this.cardInfo.accessToken
        }
      }).then(res => {
        var data = res.data.res;
        this.picList = JSON.parse(data)
        console.log("picList",this.picList)
      }).catch(err => {
        wgt.showMessage({
          title: err.msg,
          icon: 'error',
          duration: 3000
        });
      })

      // wgt.request({
      //   url: 'http://219.145.171.132:51125/szjm/getTypeInfo?sceneType=3',
      //   method: 'get',
      //   headers: {
      //     AccessToken: this.cardInfo.accessToken
      //   }
      // }).then(res => {
      //
      // })

    },
    //获取图片数据
    getImgUrl(id, deviceCode) {
      const params = {
        id,
        alertType: this.alertType,
        deviceCode
      };
      return requestApi({
        url: API_URLS.getAlarmImageUrl,
        method: 'post',
        data: params,
        headers: {
          AccessToken: this.cardInfo.accessToken
        }
      }).then(res => {
        if (res.code === 0 && res.data) {
          return res.data;
        }
      })
    },

    open(item) {
      // this.$refs.picModal?.open(item);
      this.$refs.imgModal?.openPreview('https://dianxin.minio.xiangshilian.com:9001/'+item.bgImageUrl);
    },
    openImg(imageUrl) {
      this.$refs.imgModal?.openPreview(imageUrl);
    },
    openWin() {
      window.eventBus && window.eventBus.$emit('navigate-router', this.widgetConfig.routerConfig)
    },
    // 根据id获取接口配置信息
    getDataSourceById(id) {
      return this.widgetConfig.dataSource.find(it => it.id === id);
    },
    /**
     * 获取接口响应数据，支持动态接口(extraParam为业务扩展请求参数)和静态数据
     * @param {String} id 接口配置id，唯一标识
     * @param {Object} extraParam 业务扩展请求参数
     * @returns {Object} result
     *    result.type: 'api'动态接口请求模式，'static'静态数据
     *    result.data: 数据详情
     */
    async getDataSourceResult(id, extraParam = {}) {
      let conf = this.getDataSourceById(id);
      if (!conf) return { code: -2, msg: '缺少接口配置' };
      const { request = {}, data = {} } = conf;
      // 动态接口请求
      if (request.url) {
        const res = await requestApi({
          ...request,
          data: {
            ...(request.data || {}),
            ...extraParam
          },
          headers: {
            AccessToken: this.cardInfo.accessToken,
            ...(request.headers || {})
          }
        })
        return { type: 'api', data: res };
      } else {
        // 静态数据
        return { type: 'static', data };
      }
    },
  },
  beforeDestroy() {
    window.eventBus && window.eventBus.$off('card-refresh-timer', this.refresh)

    window.eventBus && window.eventBus.$off('j-push-msg', this.getWidgetData);
  },
  components: {
    PicPanelTitle,
    PicList,
    DpModal,
    DproHeader
  },
});
